package com.java.cg.order.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.cg.goods.feign.GoodsApi;
import com.java.cg.order.constants.CartConstant;
import com.java.cg.order.dao.OrderDao;
import com.java.cg.order.entity.Order;
import com.java.cg.order.entity.OrderItem;
import com.java.cg.order.service.OrderItemService;
import com.java.cg.order.service.OrderService;
import com.java.cg.user.feign.UserApi;
import com.java.common.exception.RRException;
import com.java.common.utils.PageUtils;
import com.java.common.utils.Query;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, Order> implements OrderService {
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private OrderItemService orderItemService;
	@Autowired
	private GoodsApi goodsApi;
	@Autowired
	private UserApi userApi;
	@Autowired
	private AmqpTemplate amqpTemplate;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<Order> page = this.page(
				new Query<Order>().getPage(params),
				new QueryWrapper<>()
		);

		return new PageUtils(page);
	}

	@Override
	public void addOrder(Order order) {
		//1.添加订单表的数据
		order.setId(IdWorker.getIdStr());

//		List<OrderItem> values = redisTemplate.boundHashOps(CartConstant.CG_CART + order.getUsername()).values();
		List<Object> cartJsonList = redisTemplate.boundHashOps(CartConstant.CG_CART + order.getUsername()).values();
		List<OrderItem> orderItems = null;
		//将json字符串转换成bean
		if (!CollectionUtils.isEmpty(cartJsonList)) {
			orderItems = cartJsonList.stream().map(cartJson -> JSON.parseObject(cartJson.toString(), OrderItem.class)).collect(Collectors.toList());
		}

		Integer totalNum = 0;//购买总数量
		Integer totalMoney = 0;//购买的总金额

		Map<String, Integer> decrMap = new HashMap<>();
		for (OrderItem orderItem : orderItems) {
			totalNum += orderItem.getNum();//购买的数量
			totalMoney += orderItem.getMoney();//金额
			//2.添加订单选项表的数据
			orderItem.setId(IdWorker.getIdStr());//订单选项的iD
			orderItem.setOrderId(order.getId());//订单的iD
			orderItem.setIsReturn("0");//未退货
			orderItemService.save(orderItem);

			//封装减库存数据
			decrMap.put(orderItem.getSkuId().toString(), orderItem.getNum());
		}
		//3.减少库存  调用goods 微服务的 feign 减少库存
		goodsApi.decr(decrMap);

		order.setTotalNum(totalNum);//设置总数量
		order.setTotalMoney(totalMoney);//设置总金额
		order.setPayMoney(totalMoney);//设置实付金额
		order.setCreateTime(new Date());
		order.setUpdateTime(order.getCreateTime());
		order.setOrderStatus("0");//0:未完成
		order.setPayStatus("0");//未支付
		order.setConsignStatus("0");//未发货
		order.setIsDelete("0");//未删除
		this.baseMapper.insert(order);

		//4.增加积分  调用用户微服务的userfeign 增加积分
		userApi.addPoints(10);

		//5.清空当前的用户的redis中的购物车
		redisTemplate.delete(CartConstant.CG_CART + order.getUsername());

		// 订单创建之后发送消息到延时队列进行定时关单
		amqpTemplate.convertAndSend("CLOSE-ORDER-EXCHANGE", "order.create", order.getId());
	}

	@Override
	public void updateOrderStatus(String orderId, String transactionId, String payTime){
		Order order = this.baseMapper.selectById(orderId);
		if (order != null) {
			order.setTransactionId(transactionId);
			order.setPayTime(DateUtil.parse(payTime, "yyyyMMddHHmmss"));
			order.setPayStatus("1");
			this.baseMapper.insert(order);
		} else {
			throw new RRException("订单不存在!!");
		}
	}

	@Override
	public Integer closeOrder(String orderId) {
		return this.baseMapper.closeOrder(orderId);
	}
}